package GUI;

import util.User;
import util.UserDAO;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.RoundRectangle2D;
import java.util.Objects;

/**
 * 个人信息面板，用于显示和编辑用户个人信息
 */
public class ProfilePanel extends JPanel {
    private User currentUser;

    private JTextField nameField;
    private JTextField contactField;
    private JTextField regionField;
    private JLabel usernameValueLabel;
    private JLabel pointsValueLabel;
    private JLabel carbonReductionValueLabel;
    private JLabel levelLabel;
    private JButton saveButton;
    private JLabel messageLabel;

    // 新增字段组件
    private JComboBox<String> genderComboBox;
    private JTextField birthDateField;
    private JTextField emailField;
    private JTextField occupationField;
    private JPanel hobbiesPanel;
    private JCheckBox[] hobbyCheckboxes;
    private JComboBox<String> preferredTravelModeComboBox;
    private JProgressBar levelProgressBar;
    private JLabel nextLevelPointsLabel;
    private JButton changePasswordButton;
    private JCheckBox profilePublicCheckBox;

    // 常量定义
    private final String[] GENDERS = { "男", "女", "其他", "不愿透露" };
    private final String[] HOBBIES = { "跑步", "骑行", "徒步", "游泳", "健身", "瑜伽", "户外活动", "环保志愿" };
    private final String[] TRAVEL_MODES = { "公共交通", "骑行", "步行", "共享单车", "共享汽车", "电动车" };

    public ProfilePanel(User user) {
        this.currentUser = user;

        // 设置布局
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
        setBackground(new Color(245, 250, 245));

        // 创建标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        titlePanel.setOpaque(false);
        JLabel titleLabel = new JLabel("个人信息", JLabel.LEFT);
        titleLabel.setFont(new Font("等线", Font.BOLD, 24));
        titleLabel.setForeground(new Color(0, 120, 0));
        titlePanel.add(titleLabel);

        // 创建主要内容面板
        JPanel contentPanel = new JPanel(new BorderLayout(20, 20));
        contentPanel.setOpaque(false);

        // 创建左侧用户概览面板
        JPanel userOverviewPanel = createUserOverviewPanel();

        // 创建右侧详细信息面板
        JPanel userDetailsPanel = createUserDetailsPanel();

        // 将两个面板添加到内容面板中
        contentPanel.add(userOverviewPanel, BorderLayout.WEST);
        contentPanel.add(userDetailsPanel, BorderLayout.CENTER);

        // 创建消息标签
        messageLabel = new JLabel("", JLabel.CENTER);
        messageLabel.setFont(new Font("等线", Font.PLAIN, 14));
        JPanel messagePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        messagePanel.setOpaque(false);
        messagePanel.add(messageLabel);

        // 将所有面板添加到主面板
        add(titlePanel, BorderLayout.NORTH);
        add(contentPanel, BorderLayout.CENTER);
        add(messagePanel, BorderLayout.SOUTH);
    }

    /**
     * 创建用户概览面板
     */
    private JPanel createUserOverviewPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 绘制圆角矩形背景
                RoundRectangle2D roundedRectangle = new RoundRectangle2D.Float(
                        0, 0, getWidth(), getHeight(), 15, 15);
                g2d.setColor(new Color(220, 240, 220));
                g2d.fill(roundedRectangle);
            }
        };
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        panel.setPreferredSize(new Dimension(180, 400));

        // 创建等级图标面板，而不是头像
        JPanel levelIconPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setColor(getLevelColor(currentUser.getPoints()));
                g2d.fillOval(0, 0, 100, 100);
                g2d.setColor(Color.WHITE);
                g2d.setFont(new Font("等线", Font.BOLD, 36));
                g2d.drawString(getLevelIcon(currentUser.getPoints()), 38, 65);
            }
        };
        levelIconPanel.setPreferredSize(new Dimension(90, 90));
        levelIconPanel.setMinimumSize(new Dimension(90, 90));
        levelIconPanel.setMaximumSize(new Dimension(90, 90));
        levelIconPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(levelIconPanel);

        panel.add(Box.createVerticalStrut(15));

        // 添加用户名
        usernameValueLabel = new JLabel(currentUser.getUsername());
        usernameValueLabel.setFont(new Font("等线", Font.BOLD, 18));
        usernameValueLabel.setForeground(new Color(0, 100, 0));
        usernameValueLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(usernameValueLabel);

        panel.add(Box.createVerticalStrut(5));

        // 添加用户等级
        levelLabel = new JLabel(getUserLevel(currentUser.getPoints()));
        levelLabel.setFont(new Font("等线", Font.PLAIN, 14));
        levelLabel.setForeground(new Color(100, 100, 100));
        levelLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(levelLabel);

        panel.add(Box.createVerticalStrut(10));

        // 添加等级进度条
        levelProgressBar = new JProgressBar();
        levelProgressBar.setStringPainted(true);
        levelProgressBar.setForeground(getLevelColor(currentUser.getPoints()));
        levelProgressBar.setBackground(new Color(240, 240, 240));
        levelProgressBar.setAlignmentX(Component.CENTER_ALIGNMENT);
        levelProgressBar.setMaximumSize(new Dimension(180, 15));
        updateLevelProgress();
        panel.add(levelProgressBar);

        // 添加下一级所需积分提示
        nextLevelPointsLabel = new JLabel(getNextLevelInfo());
        nextLevelPointsLabel.setFont(new Font("等线", Font.PLAIN, 12));
        nextLevelPointsLabel.setForeground(new Color(80, 80, 80));
        nextLevelPointsLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(nextLevelPointsLabel);

        panel.add(Box.createVerticalStrut(20));

        // 添加积分信息
        JPanel pointsPanel = createInfoPanel("积分", String.valueOf(currentUser.getPoints()));
        panel.add(pointsPanel);

        panel.add(Box.createVerticalStrut(10));

        // 添加碳减排信息
        JPanel carbonPanel = createInfoPanel("碳减排量(kg)", String.format("%.2f", currentUser.getCarbonReduction()));
        panel.add(carbonPanel);

        panel.add(Box.createVerticalStrut(20));

        // 添加等级权益说明
        JLabel benefitsTitle = new JLabel("等级权益");
        benefitsTitle.setFont(new Font("等线", Font.BOLD, 14));
        benefitsTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(benefitsTitle);

        JTextArea benefitsArea = new JTextArea(getLevelBenefits());
        benefitsArea.setEditable(false);
        benefitsArea.setWrapStyleWord(true);
        benefitsArea.setLineWrap(true);
        benefitsArea.setOpaque(false);
        benefitsArea.setFont(new Font("等线", Font.PLAIN, 12));
        benefitsArea.setForeground(new Color(80, 80, 80));
        benefitsArea.setAlignmentX(Component.CENTER_ALIGNMENT);
        benefitsArea.setMaximumSize(new Dimension(180, 100));
        panel.add(benefitsArea);

        panel.add(Box.createVerticalGlue());

        return panel;
    }

    /**
     * 创建用户详细信息面板
     */
    private JPanel createUserDetailsPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 绘制圆角矩形背景
                RoundRectangle2D roundedRectangle = new RoundRectangle2D.Float(
                        0, 0, getWidth(), getHeight(), 15, 15);
                g2d.setColor(Color.WHITE);
                g2d.fill(roundedRectangle);
            }
        };

        // 使用滚动面板来容纳所有组件
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
        contentPanel.setOpaque(false);

        JScrollPane scrollPane = new JScrollPane(contentPanel);
        scrollPane.setBorder(null);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);

        panel.setLayout(new BorderLayout());
        panel.add(scrollPane, BorderLayout.CENTER);

        // 添加表单标题
        JLabel formTitle = new JLabel("个人资料");
        formTitle.setFont(new Font("等线", Font.BOLD, 18));
        formTitle.setAlignmentX(Component.LEFT_ALIGNMENT);
        contentPanel.add(formTitle);

        contentPanel.add(Box.createVerticalStrut(20));

        // 添加基本信息组
        JLabel basicInfoLabel = new JLabel("基本信息");
        basicInfoLabel.setFont(new Font("等线", Font.BOLD, 14));
        basicInfoLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        contentPanel.add(basicInfoLabel);

        contentPanel.add(Box.createVerticalStrut(10));

        // 创建两列布局的表单面板
        JPanel formGridPanel = new JPanel(new GridLayout(0, 2, 15, 15));
        formGridPanel.setOpaque(false);
        formGridPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        formGridPanel.setMaximumSize(new Dimension(600, 350));

        // 添加姓名字段
        nameField = new JTextField(currentUser.getName(), 20);
        formGridPanel.add(createFormField("姓名", nameField));

        // 添加性别选择
        genderComboBox = new JComboBox<>(GENDERS);
        if (currentUser.getGender() != null && !currentUser.getGender().isEmpty()) {
            genderComboBox.setSelectedItem(currentUser.getGender());
        }
        formGridPanel.add(createFormFieldWithComponent("性别", genderComboBox));

        // 添加出生日期字段
        birthDateField = new JTextField(currentUser.getBirthDate(), 20);
        formGridPanel.add(createFormField("出生日期 (YYYY-MM-DD)", birthDateField));

        // 添加职业字段
        occupationField = new JTextField(currentUser.getOccupation(), 20);
        formGridPanel.add(createFormField("职业", occupationField));

        // 添加联系方式字段
        contactField = new JTextField(currentUser.getContact(), 20);
        formGridPanel.add(createFormField("联系方式", contactField));

        // 添加电子邮箱字段
        emailField = new JTextField(currentUser.getEmail(), 20);
        formGridPanel.add(createFormField("电子邮箱", emailField));

        // 添加所在地区字段
        regionField = new JTextField(currentUser.getRegion(), 20);
        formGridPanel.add(createFormField("所在地区", regionField));

        // 添加表单网格到内容面板
        contentPanel.add(formGridPanel);
        contentPanel.add(Box.createVerticalStrut(25));

        // 添加兴趣爱好部分
        JLabel hobbiesLabel = new JLabel("兴趣爱好");
        hobbiesLabel.setFont(new Font("等线", Font.BOLD, 14));
        hobbiesLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        contentPanel.add(hobbiesLabel);

        contentPanel.add(Box.createVerticalStrut(10));

        // 创建兴趣爱好多选框面板
        hobbiesPanel = new JPanel(new GridLayout(0, 4, 5, 5));
        hobbiesPanel.setOpaque(false);
        hobbiesPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        hobbiesPanel.setMaximumSize(new Dimension(600, 80));

        String[] userHobbies = currentUser.getHobbies() != null ? currentUser.getHobbies().split(",") : new String[0];
        hobbyCheckboxes = new JCheckBox[HOBBIES.length];

        for (int i = 0; i < HOBBIES.length; i++) {
            hobbyCheckboxes[i] = new JCheckBox(HOBBIES[i]);
            hobbyCheckboxes[i].setOpaque(false);

            // 检查用户现有的爱好并选中对应选项
            for (String hobby : userHobbies) {
                if (HOBBIES[i].equals(hobby.trim())) {
                    hobbyCheckboxes[i].setSelected(true);
                    break;
                }
            }

            hobbiesPanel.add(hobbyCheckboxes[i]);
        }

        contentPanel.add(hobbiesPanel);
        contentPanel.add(Box.createVerticalStrut(25));

        // 添加偏好出行方式和隐私设置面板（两列）
        JPanel preferencesPanel = new JPanel(new GridLayout(0, 2, 15, 15));
        preferencesPanel.setOpaque(false);
        preferencesPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        preferencesPanel.setMaximumSize(new Dimension(600, 80));

        // 添加偏好出行方式
        JPanel travelModePanel = new JPanel();
        travelModePanel.setLayout(new BoxLayout(travelModePanel, BoxLayout.Y_AXIS));
        travelModePanel.setOpaque(false);

        JLabel travelPreferenceLabel = new JLabel("偏好出行方式");
        travelPreferenceLabel.setFont(new Font("等线", Font.BOLD, 14));
        travelPreferenceLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        travelModePanel.add(travelPreferenceLabel);

        travelModePanel.add(Box.createVerticalStrut(10));

        preferredTravelModeComboBox = new JComboBox<>(TRAVEL_MODES);
        if (currentUser.getPreferredTravelMode() != null && !currentUser.getPreferredTravelMode().isEmpty()) {
            preferredTravelModeComboBox.setSelectedItem(currentUser.getPreferredTravelMode());
        }
        preferredTravelModeComboBox.setAlignmentX(Component.LEFT_ALIGNMENT);
        preferredTravelModeComboBox.setMaximumSize(new Dimension(200, 30));
        travelModePanel.add(preferredTravelModeComboBox);

        preferencesPanel.add(travelModePanel);

        // 添加隐私与安全部分
        JPanel privacyPanel = new JPanel();
        privacyPanel.setLayout(new BoxLayout(privacyPanel, BoxLayout.Y_AXIS));
        privacyPanel.setOpaque(false);

        JLabel privacyLabel = new JLabel("隐私与安全");
        privacyLabel.setFont(new Font("等线", Font.BOLD, 14));
        privacyLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        privacyPanel.add(privacyLabel);

        privacyPanel.add(Box.createVerticalStrut(10));

        profilePublicCheckBox = new JCheckBox("公开我的个人资料");
        profilePublicCheckBox.setSelected(currentUser.isProfilePublic());
        profilePublicCheckBox.setOpaque(false);
        profilePublicCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT);
        privacyPanel.add(profilePublicCheckBox);

        preferencesPanel.add(privacyPanel);

        contentPanel.add(preferencesPanel);
        contentPanel.add(Box.createVerticalStrut(15));

        // 添加修改密码按钮和保存按钮（水平排列）
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
        buttonPanel.setOpaque(false);
        buttonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 添加修改密码按钮
        changePasswordButton = new JButton("修改密码");
        changePasswordButton.setFont(new Font("等线", Font.PLAIN, 14));
        changePasswordButton.setForeground(new Color(0, 100, 0));
        changePasswordButton.setBackground(new Color(240, 255, 240));
        changePasswordButton.setFocusPainted(false);
        changePasswordButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        changePasswordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showChangePasswordDialog();
            }
        });
        buttonPanel.add(changePasswordButton);

        // 添加保存按钮
        saveButton = new JButton("保存修改");
        saveButton.setFont(new Font("等线", Font.PLAIN, 14));
        saveButton.setBackground(new Color(0, 150, 0));
        saveButton.setForeground(Color.WHITE);
        saveButton.setFocusPainted(false);
        saveButton.setBorderPainted(false);
        saveButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveChanges();
            }
        });
        buttonPanel.add(saveButton);

        contentPanel.add(Box.createVerticalStrut(15));
        contentPanel.add(buttonPanel);

        return panel;
    }

    /**
     * 创建信息面板
     */
    private JPanel createInfoPanel(String label, String value) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setOpaque(false);
        panel.setAlignmentX(Component.CENTER_ALIGNMENT);

        JLabel titleLabel = new JLabel(label);
        titleLabel.setFont(new Font("等线", Font.PLAIN, 12));
        titleLabel.setForeground(new Color(100, 100, 100));
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(titleLabel);

        JLabel valueLabel = new JLabel(value);
        if (label.equals("积分")) {
            pointsValueLabel = valueLabel;
        } else if (label.equals("碳减排量(kg)")) {
            carbonReductionValueLabel = valueLabel;
        }
        valueLabel.setFont(new Font("等线", Font.BOLD, 16));
        valueLabel.setForeground(new Color(0, 120, 0));
        valueLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        panel.add(valueLabel);

        return panel;
    }

    /**
     * 创建表单字段
     */
    private JPanel createFormField(String labelText, JTextField textField) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setOpaque(false);
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.setMaximumSize(new Dimension(500, 70));

        JLabel label = new JLabel(labelText);
        label.setFont(new Font("等线", Font.PLAIN, 14));
        label.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.add(label);

        panel.add(Box.createVerticalStrut(5));

        textField.setFont(new Font("等线", Font.PLAIN, 14));
        textField.setAlignmentX(Component.LEFT_ALIGNMENT);
        textField.setMaximumSize(new Dimension(500, 35));
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220)),
                BorderFactory.createEmptyBorder(8, 10, 8, 10)));
        panel.add(textField);

        return panel;
    }

    /**
     * 创建带有组件的表单字段
     */
    private JPanel createFormFieldWithComponent(String labelText, JComponent component) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setOpaque(false);
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.setMaximumSize(new Dimension(500, 70));

        JLabel label = new JLabel(labelText);
        label.setFont(new Font("等线", Font.PLAIN, 14));
        label.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.add(label);

        panel.add(Box.createVerticalStrut(5));

        component.setFont(new Font("等线", Font.PLAIN, 14));
        component.setMaximumSize(new Dimension(200, 35));
        panel.add(component);

        return panel;
    }

    /**
     * 保存用户信息修改
     */
    private void saveChanges() {
        String name = nameField.getText();
        String contact = contactField.getText();
        String region = regionField.getText();
        String gender = (String) genderComboBox.getSelectedItem();
        String birthDate = birthDateField.getText();
        String email = emailField.getText();
        String occupation = occupationField.getText();
        String preferredTravelMode = (String) preferredTravelModeComboBox.getSelectedItem();
        boolean profilePublic = profilePublicCheckBox.isSelected();

        // 检查输入是否完整
        if (name.isEmpty() || contact.isEmpty() || region.isEmpty()) {
            messageLabel.setText("姓名、联系方式和地区字段必须填写！");
            messageLabel.setForeground(Color.RED);
            return;
        }

        // 验证电子邮箱格式
        if (!email.isEmpty() && !email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
            messageLabel.setText("请输入有效的电子邮箱地址！");
            messageLabel.setForeground(Color.RED);
            return;
        }

        // 验证出生日期格式
        if (!birthDate.isEmpty() && !birthDate.matches("^\\d{4}-\\d{2}-\\d{2}$")) {
            messageLabel.setText("请按YYYY-MM-DD格式输入出生日期！");
            messageLabel.setForeground(Color.RED);
            return;
        }

        // 收集选中的兴趣爱好
        StringBuilder hobbiesBuilder = new StringBuilder();
        boolean isFirst = true;

        for (JCheckBox hobbyBox : hobbyCheckboxes) {
            if (hobbyBox.isSelected()) {
                if (!isFirst) {
                    hobbiesBuilder.append(",");
                }
                hobbiesBuilder.append(hobbyBox.getText());
                isFirst = false;
            }
        }

        // 更新用户对象
        currentUser.setName(name);
        currentUser.setContact(contact);
        currentUser.setRegion(region);
        currentUser.setGender(gender);
        currentUser.setBirthDate(birthDate);
        currentUser.setEmail(email);
        currentUser.setOccupation(occupation);
        currentUser.setHobbies(hobbiesBuilder.toString());
        currentUser.setPreferredTravelMode(preferredTravelMode);
        currentUser.setProfilePublic(profilePublic);

        // 保存到数据库
        UserDAO userDAO = new UserDAO();
        boolean success = userDAO.updateUser(currentUser);

        if (success) {
            messageLabel.setText("个人信息已成功更新！");
            messageLabel.setForeground(new Color(0, 128, 0)); // 绿色
        } else {
            messageLabel.setText("更新失败，请稍后再试！");
            messageLabel.setForeground(Color.RED);
        }
    }

    /**
     * 显示修改密码对话框
     */
    private void showChangePasswordDialog() {
        JPanel panel = new JPanel(new GridLayout(3, 2, 5, 5));

        JPasswordField currentPasswordField = new JPasswordField(20);
        JPasswordField newPasswordField = new JPasswordField(20);
        JPasswordField confirmPasswordField = new JPasswordField(20);

        panel.add(new JLabel("当前密码:"));
        panel.add(currentPasswordField);
        panel.add(new JLabel("新密码:"));
        panel.add(newPasswordField);
        panel.add(new JLabel("确认新密码:"));
        panel.add(confirmPasswordField);

        int result = JOptionPane.showConfirmDialog(
                this, panel, "修改密码",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

        if (result == JOptionPane.OK_OPTION) {
            String currentPassword = new String(currentPasswordField.getPassword());
            String newPassword = new String(newPasswordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());

            // 验证当前密码
            if (!currentPassword.equals(currentUser.getPassword())) {
                JOptionPane.showMessageDialog(this, "当前密码不正确！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 验证新密码格式
            if (newPassword.length() < 8) {
                JOptionPane.showMessageDialog(this, "新密码长度必须至少为8个字符！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 验证两次输入的新密码是否一致
            if (!newPassword.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(this, "两次输入的新密码不一致！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 更新密码
            currentUser.setPassword(newPassword);
            UserDAO userDAO = new UserDAO();
            boolean success = userDAO.updateUserPassword(currentUser.getId(), newPassword);

            if (success) {
                JOptionPane.showMessageDialog(this, "密码已成功更新！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "密码更新失败，请稍后再试！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * 刷新用户数据
     */
    public void refreshData() {
        UserDAO userDAO = new UserDAO();
        User refreshedUser = userDAO.getUserById(currentUser.getId());
        if (refreshedUser != null) {
            currentUser = refreshedUser;
            // 更新显示的用户信息
            usernameValueLabel.setText(currentUser.getUsername());
            nameField.setText(currentUser.getName());
            contactField.setText(currentUser.getContact());
            regionField.setText(currentUser.getRegion());
            pointsValueLabel.setText(String.valueOf(currentUser.getPoints()));
            carbonReductionValueLabel.setText(String.format("%.2f", currentUser.getCarbonReduction()));
            levelLabel.setText(getUserLevel(currentUser.getPoints()));

            // 更新新增字段
            if (currentUser.getGender() != null && !currentUser.getGender().isEmpty()) {
                genderComboBox.setSelectedItem(currentUser.getGender());
            }
            birthDateField.setText(currentUser.getBirthDate());
            emailField.setText(currentUser.getEmail());
            occupationField.setText(currentUser.getOccupation());

            // 更新兴趣爱好选择
            String[] userHobbies = currentUser.getHobbies() != null ? currentUser.getHobbies().split(",")
                    : new String[0];
            for (int i = 0; i < hobbyCheckboxes.length; i++) {
                hobbyCheckboxes[i].setSelected(false);
                for (String hobby : userHobbies) {
                    if (HOBBIES[i].equals(hobby.trim())) {
                        hobbyCheckboxes[i].setSelected(true);
                        break;
                    }
                }
            }

            // 更新偏好出行方式
            if (currentUser.getPreferredTravelMode() != null && !currentUser.getPreferredTravelMode().isEmpty()) {
                preferredTravelModeComboBox.setSelectedItem(currentUser.getPreferredTravelMode());
            }

            // 更新隐私设置
            profilePublicCheckBox.setSelected(currentUser.isProfilePublic());

            // 更新等级进度条
            updateLevelProgress();
            nextLevelPointsLabel.setText(getNextLevelInfo());
        }
    }

    /**
     * 根据积分计算用户等级
     */
    private String getUserLevel(int points) {
        if (points < 100) {
            return "初级绿行者";
        } else if (points < 500) {
            return "中级绿行者";
        } else if (points < 1000) {
            return "高级绿行者";
        } else if (points < 2000) {
            return "绿行达人";
        } else {
            return "绿行大师";
        }
    }

    /**
     * 获取等级图标文本
     */
    private String getLevelIcon(int points) {
        if (points < 100) {
            return "初";
        } else if (points < 500) {
            return "中";
        } else if (points < 1000) {
            return "高";
        } else if (points < 2000) {
            return "达";
        } else {
            return "大";
        }
    }

    /**
     * 获取等级颜色
     */
    private Color getLevelColor(int points) {
        if (points < 100) {
            return new Color(119, 178, 85); // 浅绿色
        } else if (points < 500) {
            return new Color(76, 175, 80); // 绿色
        } else if (points < 1000) {
            return new Color(0, 150, 136); // 蓝绿色
        } else if (points < 2000) {
            return new Color(3, 169, 244); // 蓝色
        } else {
            return new Color(156, 39, 176); // 紫色
        }
    }

    /**
     * 更新等级进度条
     */
    private void updateLevelProgress() {
        int points = currentUser.getPoints();
        int currentLevelMin = 0;
        int nextLevelMin = 100;

        if (points < 100) {
            currentLevelMin = 0;
            nextLevelMin = 100;
        } else if (points < 500) {
            currentLevelMin = 100;
            nextLevelMin = 500;
        } else if (points < 1000) {
            currentLevelMin = 500;
            nextLevelMin = 1000;
        } else if (points < 2000) {
            currentLevelMin = 1000;
            nextLevelMin = 2000;
        } else {
            currentLevelMin = 2000;
            nextLevelMin = 2000; // 已经是最高级
            levelProgressBar.setValue(100);
            levelProgressBar.setString("已达最高级");
            return;
        }

        int progress = (int) (((double) (points - currentLevelMin) / (nextLevelMin - currentLevelMin)) * 100);
        levelProgressBar.setValue(progress);
        levelProgressBar.setString(progress + "%");
    }

    /**
     * 获取下一等级信息
     */
    private String getNextLevelInfo() {
        int points = currentUser.getPoints();

        if (points < 100) {
            return "距离中级绿行者还需 " + (100 - points) + " 积分";
        } else if (points < 500) {
            return "距离高级绿行者还需 " + (500 - points) + " 积分";
        } else if (points < 1000) {
            return "距离绿行达人还需 " + (1000 - points) + " 积分";
        } else if (points < 2000) {
            return "距离绿行大师还需 " + (2000 - points) + " 积分";
        } else {
            return "已达最高级别";
        }
    }

    /**
     * 获取等级权益说明
     */
    private String getLevelBenefits() {
        int points = currentUser.getPoints();

        if (points < 100) {
            return "初级绿行者：可查看绿色出行路线，享受基础积分奖励。";
        } else if (points < 500) {
            return "中级绿行者：额外10%积分奖励，可参与月度绿色活动。";
        } else if (points < 1000) {
            return "高级绿行者：额外25%积分奖励，优先参与特别活动，每月获得生态礼品。";
        } else if (points < 2000) {
            return "绿行达人：额外50%积分奖励，专属身份标识，参与绿色出行规划讨论。";
        } else {
            return "绿行大师：双倍积分奖励，专属身份标识，参与平台决策，获得年度生态大奖提名资格。";
        }
    }
}
